package com.ciaj.module.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ciaj.base.bean.BaseServiceImpl;
import com.ciaj.base.comm.constant.DefaultConstant;
import com.ciaj.base.comm.utils.CollectionUtil;
import com.ciaj.module.sys.entity.po.SysPermission;
import com.ciaj.module.sys.entity.po.SysRole;
import com.ciaj.module.sys.entity.po.SysRolePermissionRel;
import com.ciaj.module.sys.mapper.SysPermissionMapper;
import com.ciaj.module.sys.service.ISysPermissionService;
import com.ciaj.module.sys.service.ISysRolePermissionRelService;
import com.ciaj.module.sys.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 权限信息表 Gen 服务实现类
 * </p>
 *
 * @author ciaj.
 * @since 2020-08-14
 */
@Service
public class SysPermissionServiceImpl extends BaseServiceImpl<SysPermissionMapper, SysPermission> implements ISysPermissionService {
    @Autowired
    private ISysRoleService iSysRoleService;
    @Autowired
    private ISysRolePermissionRelService iSysRolePermissionRelService;

    @Override
    public Set<String> getPermissionCodesByJobId(String jobId) {
        Set<String> codes = CollectionUtil.of(getPermissionsByJobId(jobId)).map(SysPermission::getPermissionCode).collect(Collectors.toSet());
        return codes;
    }

    @Override
    public List<SysPermission> getPermissionsByJobId(String jobId) {
        List<SysRole> roles = iSysRoleService.getRolesByJobId(jobId);

        List<String> roleIds = CollectionUtil.of(roles).map(SysRole::getId).collect(Collectors.toList());

        List<SysRolePermissionRel> rolePermissionRels = iSysRolePermissionRelService.list(new QueryWrapper<SysRolePermissionRel>().lambda().in(CollectionUtil.isNotEmpty(roleIds), SysRolePermissionRel::getRoleId, roleIds));

        Set<String> permissionIds = CollectionUtil.of(rolePermissionRels).map(SysRolePermissionRel::getRoleId).collect(Collectors.toSet());

        List<SysPermission> permissions = list(new QueryWrapper<SysPermission>().lambda().eq(SysPermission::getAvailable, DefaultConstant.FLAG_Y).in(SysPermission::getId, permissionIds));
        return permissions;
    }
}
